package org.example.demo3.server.Controller;

import lombok.extern.slf4j.Slf4j;
import org.example.demo3.common.constant.JwtClaimsConstant;
import org.example.demo3.common.properties.JwtProperties;
import org.example.demo3.common.utils.JwtUtil;
import org.example.demo3.pojo.dto.AdminLoginDTO;
import org.example.demo3.common.result.Result;
import org.example.demo3.pojo.dto.AdminRegisterDTO;
import org.example.demo3.pojo.dto.AdminUpdateDTO;
import org.example.demo3.pojo.entity.Admin;
import org.example.demo3.pojo.vo.AdminLoginVO;
import org.example.demo3.pojo.vo.AdminVO;
import org.example.demo3.server.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.kafka.KafkaProperties;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private JwtProperties jwtProperties;  //此为component,已在容器中

    @Autowired
    private AdminService adminService;

    /**
     * 登录功能
     * @param adminLoginDTO
     * @return
     */
    @PostMapping("/login")
    public Result<AdminLoginVO> adminLogin(@RequestBody AdminLoginDTO adminLoginDTO){
        log.info("开始执行登录操作，账号为：{}，密码为：{}",adminLoginDTO.getUsername(),adminLoginDTO.getPassword());
        Admin admin=adminService.adminLogin(adminLoginDTO);

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.EMP_ID, admin.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);

        AdminLoginVO adminLoginVO=AdminLoginVO.builder()
                .id(admin.getId())
                .name(admin.getName())
                .userName(admin.getUsername())
                .token(token).build();

        return Result.success(adminLoginVO);
    }

    /**
     * 注册功能
     * @param adminRegisterDTO
     * @return
     */
    @PostMapping("/register")
    public Result adminRegister(@RequestBody AdminRegisterDTO adminRegisterDTO){
        log.info("register:,username:{},password:{}",adminRegisterDTO.getUsername(),adminRegisterDTO.getPassword());
        adminService.adminRegister(adminRegisterDTO);
        return Result.success();
    }

    /**
     * 用户信息查询
     * @param name
     * @return
     */
    @GetMapping("/query")
    public Result<AdminVO> adminQuery(String name){
        log.info("bengin to query admin information...");
        AdminVO adminVO=adminService.adminQuery(name);
        return Result.success(adminVO);
    }

    @PostMapping("/img")
    public Result imgUpdata(@RequestBody AdminUpdateDTO adminUpdateDTO){
        log.info("bengin to change img...img:{}, name:{}",adminUpdateDTO.getImg(),adminUpdateDTO.getName());
        adminService.imgUpdate(adminUpdateDTO);
        return Result.success();
    }
}
